package gw.com.android.terminal;

import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;

import gw.com.android.app.AppMain;
import www.com.library.app.Logger;
import www.com.library.util.Base64Utils;
import www.com.library.util.RsaBCUtil;

/**
 * 加密方法
 * Created by reeta.zou on 2016/8/31.
 */
public class RSAUtils {

    public static String RSA(String param, String pName){
        // 从资源文件中加载RSA加密公钥
        InputStream inPublic = null;
        PublicKey publicKey = null;
        String mKeyParam = "";
        Logger.e("param == " + param);
        try {
            String name = "";
            if(null == pName || pName.length() < 1){
                name = "1024_public.pem";
            }else{
                name = pName + ".pem";
            }
            inPublic = AppMain.getApp().getResources().getAssets().open(name);
            publicKey = RsaBCUtil.loadPublicKey(inPublic);
            // 将加密公钥转换为base64位
            byte[] encryptByte = RsaBCUtil.encrypt(publicKey, param.getBytes("UTF-8"));
            mKeyParam = Base64Utils.encode(encryptByte);
            mKeyParam =  java.net.URLEncoder.encode(mKeyParam, "UTF-8");
            if(null != inPublic){
                inPublic.close();
            }
            return mKeyParam;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return param;
    }

    public static byte[] RSA2(String param, String pName){
        // 从资源文件中加载RSA加密公钥
        InputStream inPublic = null;
        PublicKey publicKey = null;
        String mKeyParam = "";
        Logger.e("param == " + param);
        try {
            String name = "";
            if(null == pName || pName.length() < 1){
                name = "1024_public.pem";
            }else{
                name = pName + ".pem";
            }
            inPublic = AppMain.getApp().getResources().getAssets().open(name);
            publicKey = RsaBCUtil.loadPublicKey(inPublic);
            // 将加密公钥转换为base64位
            byte[] encryptByte = RsaBCUtil.encrypt(publicKey, param.getBytes("UTF-8"));
//            mKeyParam = Base64Utils.encode(encryptByte);
//            mKeyParam =  java.net.URLEncoder.encode(mKeyParam, "UTF-8");
            if(null != inPublic){
                inPublic.close();
            }
            return encryptByte;
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
